#
# $Id$
#
# RTEMS Project (http://www.rtems.org/)
# Copyright 2007 Chris Johns (chrisj@rtems.org)
# All rights reserved.
#
# This file is part of Builder.
#
# Foobar is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Foobar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# Builder environment defines the local build system.
#

import os
import platform
import sys

# MacOS has Python 2.3 installed by default. Provide the
# Python 2.4 modules not in Python 2.3.
if sys.version_info[0] <= 2 and sys.version_info[1] <= 4:
    sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'python2.4'))

import config
import error

class system:
    """Load the environment with the things needed to build on this
    platform."""
    def __init__(self, cfg, what = 'builder', verbose = False):
        self.what = what
        self.environ = {}
        # Get the type of system we have. This is used to find the various
        # system specific data.
        system = platform.system().lower()
        if system == 'darwin':
            # We have a MacOS system. Lets use that label rather than Darwin
            system = 'macos'
        if not cfg.has_element(self.what, 'systems', system):
            raise error.general(self.what + ' system not listed: ' + system)
        self.environ['system'] = system
        # Update the environment's paths
        self.update_path(cfg, verbose)
        self.find_tools(cfg, verbose)
        
    def find_tools(self, cfg, verbose):
        """Look for the various tools and create full paths for them.
        A system defined path overrides the user's evironment path."""
        # Always search for no extension first
        exeexts = [('path', '', 0)] + cfg.get_member(self.get('system'), 'exeexts')
        tools = cfg.get_member(self.get('system'), 'tools')
        self.environ['tool'] = {}
        if tools:
            paths[len(paths):] = os.environ['PATH'].split(os.pathsep)
            if verbose:
                output = 'Paths:' + os.linesep
                for p in paths:
                    output += ' ' + p + os.linesep
                print output
            # Check each tool by seeing if it is an absolute file or in a path
            # or if it has an extension.
            for t in tools:
                found = False
                for e in exeexts:
                    f = t[1] + e[1]
                    if os.path.isabs(f) and os.path.isfile(f):
                        name = os.path.splitext(os.path.basename(f))[0]
                        self.environ['tool'][name] = f
                        found = True
                        break
                    else:
                        # Search the paths
                        for p in paths:
                            pf = os.path.join(p, f)
                            if os.path.isfile(pf):
                                name = os.path.splitext(os.path.basename(f))[0]
                                self.environ['tool'][name] = pf
                                found = True
                                break
                    if found:
                        break
                if not found:
                    raise error.general("tool '" + t[1] + "' not found")
        if verbose and len(self.environ['tool']):
            output = 'Tools:' + os.linesep
            for t in self.environ['tool']:
                output += ' ' + t + ' -> ' + self.environ['tool'][t] + os.linesep
            print output

    def update_path(self, cfg, verbose):
        """Look got 'path' for the 'system' and update the environment."""
        if cfg.has_member(self.get('system'), 'path'):
            for p in cfg.get_member(self.get('system'), 'path'):
                os.environ['PATH'] = os.path.normpath(p[1]) + os.pathsep + os.environ['PATH']

    def __str__(self):
        output = ''
        for e in self.environ:
            output += e + ': ' + str(self.environ[e]) + os.linesep
        return output
            
    def get(self, var):
        """Get the requested variable from the environment."""
        if var in self.environ:
            return self.environ[var]
        return None
